import { apiClient } from '@/api/axios'

// 用户偏好设置接口
export interface UserPreferences {
  [key: string]: any
}

// 获取用户偏好设置
export function getUserPreferences(): Promise<{ preferences: UserPreferences }> {
  return apiClient.get('/system-configs/user-preferences').then(response => response.data)
}

// 保存用户偏好设置
export function saveUserPreferences(preferences: UserPreferences): Promise<{ message: string; saved_count: number }> {
  return apiClient.post('/system-configs/user-preferences', {
    preferences
  }).then(response => response.data)
}

// 保存列设置
export function saveColumnSettings(viewName: string, settings: { columns: string[], customFields: number[] }): Promise<{ message: string; saved_count: number }> {
  return saveUserPreferences({
    [`${viewName}_columns`]: settings.columns,
    [`${viewName}_customFields`]: settings.customFields
  })
}

// 获取列设置
export function getColumnSettings(viewName: string): Promise<{ columns: string[], customFields: number[] }> {
  return getUserPreferences().then(response => {
    const preferences = response.preferences || {}
    return {
      columns: preferences[`${viewName}_columns`] || [],
      customFields: preferences[`${viewName}_customFields`] || []
    }
  })
}

// 保存查询字段设置
export function saveSearchFieldSettings(viewName: string, settings: { searchFields: string[], searchCustomFields: number[] }): Promise<{ message: string; saved_count: number }> {
  return saveUserPreferences({
    [`${viewName}_searchFields`]: settings.searchFields,
    [`${viewName}_searchCustomFields`]: settings.searchCustomFields
  })
}

// 获取查询字段设置
export function getSearchFieldSettings(viewName: string): Promise<{ searchFields: string[], searchCustomFields: number[] }> {
  return getUserPreferences().then(response => {
    const preferences = response.preferences || {}
    return {
      searchFields: preferences[`${viewName}_searchFields`] || [],
      searchCustomFields: preferences[`${viewName}_searchCustomFields`] || []
    }
  })
}